package com.gm.wj.service;

import com.gm.wj.config.RedisConfig;
import com.gm.wj.dao.SysLogDAO;
import com.gm.wj.entity.SysLog;
import com.gm.wj.redis.RedisService;
import com.gm.wj.util.MyPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @program: wj
 * @description: 系统日志
 * @author: Huang_shengjun
 * @create: 2020-12-10 17:23
 **/
@Slf4j
@Service
public class SysLogService {
    @Autowired
    SysLogDAO sysLogDAO;
    @Autowired
    RedisService redisService;
    @Autowired
    PermissionURL permissionURL;

    public int addOrUpdate(SysLog sysLog) {
        sysLogDAO.save(sysLog);
        redisService.delete("sysLogs" + sysLog.getId());
        Set<String> keys = redisService.getKeysByPattern("sysLogspage*");
        redisService.delete(keys);
        return 1;
    }

    public MyPage list(int page, int size) {
        MyPage<SysLog> sysLogs;
        // list缓存
        String key = "sysLogspage:" + page;
        Object pageCache = redisService.get(key);

        // 如果为空，就再查询一次，写入redis缓存
        if (pageCache == null) {
            Sort sort = Sort.by(Sort.Direction.DESC, "id");
            Page<SysLog> InDb = sysLogDAO.findAll(PageRequest.of(page, size, sort));
            sysLogs = new MyPage<>(InDb);
            // 设置redis过期时间  5s
            redisService.set(key, sysLogs, RedisConfig.DATA_REDIS_KEY_TIME);
        } else {
            sysLogs = (MyPage<SysLog>) pageCache;
        }
        return sysLogs;
    }

    public int findLogData() {
        return sysLogDAO.countByLog();
    }
}
